import { _decorator, instantiate, Prefab, Node } from 'cc';
const { ccclass, property } = _decorator;

import { bdlMgr } from "../../../../Script/Manager/BundleManager_S";
import { Minesweeper_GameData } from "../Data/Minesweeper_GameData";
import Minesweeper_Block from "./Minesweeper_Block";
import Minesweeper_GameManager from "./Minesweeper_GameManager";
import Minesweeper_Grid from "./Minesweeper_Grid";

@ccclass('MinesweeperCardFunctions')
export default class Minesweeper_CardFunctions {
    //    /** 创建格子 */
    static async CreateGrid(_col: number, _row: number, _id) {
        const prefab = await bdlMgr.getRes<Prefab>(`Minesweeper_Prefab`, `Grid`, Prefab);
        const node: Node = instantiate(prefab);
        const scrGrid: Minesweeper_Grid = node.getComponent(Minesweeper_Grid);
        scrGrid.init(_col, _row, _id);
        Minesweeper_GameManager.Instance.Root_grid.addChild(node);
        return scrGrid;
    }
    //    /** 创建牌组 */
    static async CreateBlock(_col: number, _row: number, _point: number) {
        const prefab = await bdlMgr.getRes<Prefab>(`Minesweeper_Prefab`, `Block`, Prefab);
        const node: Node = instantiate(prefab);
        const block: Minesweeper_Block = node.getComponent(Minesweeper_Block);
        Minesweeper_GameManager.Instance.Root_block.addChild(node);
        block.init(_col, _row, _point);
        return block;
    }
    static async 随机空地生成一个方块(_id: number) {
        // let arr = Minesweeper_CardFunctions.获取所有空地();
        // // console.log(`arr`, arr);
        // let r = randomRangeInt(0, arr.length);
        // let grid = arr[r];
        // // console.log(`grid`, grid);

        // const scrBlock: S2048_Block = await Minesweeper_CardFunctions.CreateBlock(grid.col, grid.row, _id);
        // Minesweeper_GameData.arrBlocks.push(scrBlock);

        // return scrBlock;
    }
    // static async 指定地生成一个方块(_col: number, _row: number, _id: number) {
    //     const scrBlock: S2048_Block = await Minesweeper_CardFunctions.CreateBlock(_col, _row, _id);
    //     S2048_GameData.arrBlocks.push(scrBlock);
    // }
    static GetGrid(_col: number, _row: number) {
        // return S2048_GameData.arrBlocks.flat()
        //     .find(element => element.col === _col && element.row === _row);

        return Minesweeper_GameData.arrGrids.find(e => e.col == _col && e.row == _row);

        // if (S2048_GameData.arrGrids[x] && S2048_GameData.arrGrids[x][y]) {
        //     return S2048_GameData.arrGrids[x][y];
        // }

        return null;
    }
    static GetBlock(_col: number, _row: number) {
        return Minesweeper_GameData.arrBlocks.find(e => e.col == _col && e.row == _row);
    }
    static 当前格子是否是空地(_col, _row) {
        let block = Minesweeper_CardFunctions.GetBlock(_col, _row);
        if (block) {
            return false;
        }
        else {
            return true;
        }
    }
    static 获取所有空地() {
        let arr = [];
        for (let _col = 1; _col <= Minesweeper_GameData.col; _col++) {
            for (let _row = 1; _row <= Minesweeper_GameData.row; _row++) {
                const is_empty = Minesweeper_CardFunctions.当前格子是否是空地(_col, _row);
                if (is_empty) {
                    let grid: Minesweeper_Grid = Minesweeper_CardFunctions.GetGrid(_col, _row);
                    arr.push(grid);
                }
            }
        }

        return arr;
    }
    static 获取所有非空地() {
        let arr = [];
        for (let x = 0; x < Minesweeper_GameData.col; x++) {
            for (let y = 0; y < Minesweeper_GameData.row; y++) {
                const is_empty = Minesweeper_CardFunctions.当前格子是否是空地(x, y);
                if (!is_empty) {
                    let grid: Minesweeper_Grid = Minesweeper_CardFunctions.GetGrid(x, y);
                    arr.push(grid);
                }
            }
        }

        return arr;
    }
    static CheckEnd() {
        let 是否结束 = Minesweeper_CardFunctions.检查游戏是否结束();
        if (是否结束) {
            Minesweeper_GameManager.Instance.Lose();
        }
    }
    static 检查游戏是否结束() {
        for (let col = 1; col <= Minesweeper_GameData.col; col++) {
            for (let row = 1; row <= Minesweeper_GameData.row; row++) {
                const currentBlock = Minesweeper_CardFunctions.GetBlock(col, row);

                // 1. 检查当前是否为空
                if (!currentBlock || currentBlock.removed) {
                    return false; // 有空位，游戏继续
                }

                // 2. 检查右侧和下侧是否可以合并（避免重复检查左和上）
                if (col < Minesweeper_GameData.col) {
                    const rightBlock = Minesweeper_CardFunctions.GetBlock(col + 1, row);
                    if (rightBlock && rightBlock.id === currentBlock.id) {
                        return false; // 可右合并
                    }
                }

                if (row < Minesweeper_GameData.row) {
                    const bottomBlock = Minesweeper_CardFunctions.GetBlock(col, row + 1);
                    if (bottomBlock && bottomBlock.id === currentBlock.id) {
                        return false; // 可下合并
                    }
                }
            }
        }

        // 所有格子满且无法合并，游戏结束
        return true;
    }

    static 恢复所有block状态() {
        let array = Minesweeper_CardFunctions.findDuplicateItems(Minesweeper_GameData.arrBlocks);
        // console.log(`arr`, array);

        for (let index = 0; index < Minesweeper_GameData.arrBlocks.length; index++) {
            const block = Minesweeper_GameData.arrBlocks[index];
            // block.isComplete = false;
            block.merged = false;
            block.removed = false;
        }
    }
    static findDuplicateItems(arr) {
        const map = new Map<string, any[]>();

        for (const item of arr) {
            const key = `${item.row}_${item.col}`; // 创建复合键
            if (!map.has(key)) {
                map.set(key, []);
            }
            map.get(key)!.push(item);
        }

        // 只返回有重复的组
        return Array.from(map.values()).filter(group => group.length > 1);
    }
    static GetRowCard(_row: number) {
        const cards = Minesweeper_GameData.arrBlocks.filter(item => item.row == _row);
        // console.log(`cards`, cards);
        return cards;
    }
    static GetColCard(_col: number) {
        const cards = Minesweeper_GameData.arrBlocks.filter(item => item.col == _col);
        // console.log(`cards`, cards);
        return cards;
    }
}

// // /** 调试 */
window["Minesweeper_CardFunctions"] = Minesweeper_CardFunctions;